package com.example.demo.web;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.example.demo.dao.ApplicationDao;
import com.example.demo.dao.UserDao;
import com.example.demo.entity.ApplicationEntity;
import com.example.demo.entity.Constant;
import com.example.demo.entity.SysUser;

@RestController
@RequestMapping("/activitiController")
public class ActivitiController {

	private static final Logger logger = LoggerFactory.getLogger(ActivitiController.class);
	@Autowired
	private UserDao userDao ;
	
	@Autowired
	private RuntimeService runtimeService;
	
	@Autowired
	private TaskService taskService;
	
	@Autowired
	private ApplicationDao applicationDao;
	
	private SysUser getUser(){
		String zhangKaiFeng = "3490e627f4054754a1dda7d798234d58";
		SysUser user = userDao.findById(zhangKaiFeng).get();
		System.out.println(user);
		return user;
	}
	
	@RequestMapping(value = "toactiviti")
	public ModelAndView toActiviti(){
//		DetachedCriteria dc = DetachedCriteria.forClass(SysUser.class);
//		dc.add(Restrictions.eq(propertyName, value))
		System.out.println("---->toactiviti");
		return new ModelAndView("toActivitiForm.html");
	}
	
	@RequestMapping(value = "doactiviti")
	public String doActiviti(){
		//启动流程实例
		ApplicationEntity application = new ApplicationEntity();
		application.setId("121040ab230e4f76ba9f26f2a50bd290");
		Date date = new Date();
		application.setDate(date);
		application.setUser(getUser());
		application.setTitle("_"+getUser().getName());
		application.setStatus(ApplicationEntity.APPROVALING);
//		applicationDao.save(application);
		System.out.println(application);
		Map<String, Object> variables = new HashMap<String,Object>();
		variables.put("app", application);
		System.out.println(variables);
//		variables.put("application.user.id", application.getUser().getId());
		ProcessInstance startProcessInstanceByKey = runtimeService.startProcessInstanceByKey("qjlc",variables);

		TaskQuery query = taskService.createTaskQuery();
		query.taskAssignee(application.getUser().getName());
		Task task = query.list().get(0);
		taskService.complete(task.getId());
		query.processInstanceId(startProcessInstanceByKey.getId());
		logger.info("-----------------申请成功---------------");
		return "success";
	}

}
